from django.shortcuts import render
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin,RetrieveModelMixin
from . import models
from .serializer import CourseCategorySerializer,CourseSerializer,CourseSectionSerializer,CourseChapterSerializer
from .page import CommonPageNumberPagination
from rest_framework.filters import OrderingFilter,SearchFilter
from django_filters.rest_framework import DjangoFilterBackend

# 查看课程分类接口
class CourseCategoryViewSet(GenericViewSet, ListModelMixin):
    queryset = models.CourseCategory.objects.all().filter(is_delete=False, is_show=True).order_by('orders')
    serializer_class = CourseCategorySerializer


# 查看所有课程和查询单个课程接口
class CourseViewSet(GenericViewSet,ListModelMixin,RetrieveModelMixin):
    queryset = models.Course.objects.all().filter(is_delete=False,is_show=True).order_by('orders')
    serializer_class = CourseSerializer
    # 带分页
    pagination_class = CommonPageNumberPagination
    # 排序功能：学生人数，id,价格
    filter_backends = [OrderingFilter,DjangoFilterBackend]
    ordering_fields = ['id','students','price']

    # 支持过滤，按课程分类过滤：需要借助于django_filter
    # http://127.0.0.1:8080/api/v1/course/actual/?course_category=2
    filter_fields = ['course_category']


# 查询章节接口
class CourseChapterViewSet(GenericViewSet,ListModelMixin):
    queryset = models.CourseChapter.objects.all().filter(is_delete=False,is_show=True).order_by('orders')
    serializer_class = CourseChapterSerializer
    # 根据课程过滤
    filter_backends = [DjangoFilterBackend]
    filter_fields = ['course']


# 搜索接口
class CourseSearchViewSet(GenericViewSet,ListModelMixin,RetrieveModelMixin):
    queryset = models.Course.objects.all().filter(is_delete=False,is_show=True).order_by('orders')
    serializer_class = CourseSerializer
    # 分页
    pagination_class = CommonPageNumberPagination
    # 过滤
    filter_backends = [SearchFilter]
    search_fields = ['name','brief']

    # 如果想全文检索----》只要在brief中有关键字，就能搜索出来---》类似于百度
    # 如果使用mysql的like搜索，数据量越大，速度越慢
    # 后期咱们需要使用专业的搜索引擎---》Elasticsearch：分布式全文检索引擎

    # 如果这个搜索接口，返回多种课程，重写list
    # def list(self, request, *args, **kwargs):
    #     # 只返回了实战课，后期有免费，轻课，一次性返回
    #
    #     response=super().list(request, *args, **kwargs)
    #     # response.data
    #
    #     # [{},{},{}]--->{'actual_course':[],'free_course':[],'lite_course':[]}
    #     res={'actual_course':response.data,'free_course':[],'lite_course':[]}
    #     return Response(data=res)




